import axiosInstance from './axiosInstance';
import { User } from '@/features/auth/authSlice';
import { ApiResponse } from '@/types/api'; // 从共享类型文件导入
import { envConfig } from '@/config/env';

// 登录请求参数类型
interface LoginApiParams {
  username: string;
  password: string;
}

// 登录响应数据类型
interface LoginResponse {
  success: boolean;
  user?: User | null;
  token?: string;
  message?: string;
}


// 给 login 函数显式指定返回类型为 Promise<LoginResponse>
export const login = async (
  params: LoginApiParams 
): Promise<LoginResponse> => { 
  const { username, password } = params;
  if (envConfig.mockEnable) {
    // 原有 Mock 逻辑（不变）
    if ((username === 'admin' && password === 'admin123') || (username === 'user' && password === 'user123')) {
      return { 
        success: true, 
        token: 'mock-token', 
        user: { username, role: username === 'admin' ? 'admin' : 'user' } as User 
      };
    }
    return { 
      success: false, 
      message: '用户名或密码错误', 
      user: null 
    };
  }

  // 关键：补充 mockEnable = false 时的返回值（开发阶段临时用）
  return {
    success: false,
    message: '未启用 Mock 模式，请配置后端接口后使用',
    user: null
  };

  // 后续对接真实后端时，再替换成下面的代码（删除临时返回）：
  // const response = await axiosInstance.post('/auth/login', { username, password });
  // return {
  //   success: response.data.code === 200,
  //   token: response.data.data?.token,
  //   user: response.data.data?.user,
  //   message: response.data.message
  // };
};


// /**
//  * 用户登录接口
//  */
// export const login = async (params: LoginParams): Promise<LoginResponseData> => {
//   const response: ApiResponse<LoginResponseData> = await axiosInstance.post('/auth/login', params);

//   if (response.success && response.data.token) {
//     setToken(response.data.token);
//   }

//   return response.data;
// };

/**
 * 用户登出接口
 */
export const logout = async (): Promise<void> => {
  await axiosInstance.post('/auth/logout');
};

/**
 * 获取当前用户信息
 */
export const getCurrentUser = async (): Promise<User> => {
  const response: ApiResponse<User> = await axiosInstance.get('/auth/current-user');
  return response.data;
};
